﻿using AutoMapper;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using RBAC.ApiReads.Application.Command;
using RBAC.ApiReads.DTO;
using RBAC.Domain.RbacEntity;
using RBAC.Infrasturcture.Interfaces;
using RBAC.ResultCode;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace RBAC.ApiReads.Application.Commandhandler
{
    public class GetRolePermissionCommandhandler : IRequestHandler<GetRolePermissionCommand, ApiResult<ApiPaging<List<RolePermissionDTO>>>>
    {
        private readonly IBaseRepository<Permission> permissionrepository;
        private readonly IBaseRepository<Role> rolerepository;
        private readonly IBaseRepository<RolePermission> rolepermissionrepository;
        private readonly IMapper mapper;

        public GetRolePermissionCommandhandler(IBaseRepository<Permission> permissionrepository,IBaseRepository<Role> rolerepository,IBaseRepository<RolePermission> rolepermissionrepository,IMapper mapper)
        {
            this.permissionrepository = permissionrepository;
            this.rolerepository = rolerepository;
            this.rolepermissionrepository = rolepermissionrepository;
            this.mapper = mapper;
        }
        public async Task<ApiResult<ApiPaging<List<RolePermissionDTO>>>> Handle(GetRolePermissionCommand request, CancellationToken cancellationToken)
        {

            var info =  rolerepository.GetAll();
            if (!string.IsNullOrEmpty(request.RoleName))
            {

                info = info.Where(x => x.RoleName == request.RoleName);
            }


   
         
            //总条数
            int TotalCount= info.Count();
            //总页数
            int TotalPage = (int)Math.Ceiling(1.0*TotalCount/request.PageSize);
            //数据
            var list = info.OrderBy(x => x.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            var data = mapper.Map<List<RolePermissionDTO>>(list);
            //显示的是角色权限的信息  根据角色id查中间表的权限id 因为是一个角色多个权限所以得用循环
            foreach (var item in data)
            {
                var permissionidlist = rolepermissionrepository.GetAll().Where(x => x.RoleId == item.RoleId).Select(x => x.PermissionId).ToList();
                item.PermissionId = permissionidlist;
                var permissionnamelist = permissionrepository.GetAll().Where(x => permissionidlist.Contains(x.PermissionId)).Select(x => x.PermissionName).ToList();
                item.PermissionName = permissionnamelist;
            }
            return new ApiResult<ApiPaging<List<RolePermissionDTO>>>
            {
                Code = ApiResultEnum.查询成功,
                Message = ApiResultEnum.查询成功.ToString(),
                Data = new ApiPaging<List<RolePermissionDTO>>
                {
                     Data= data,
                      TotalCount=TotalCount,
                       TotalPage=TotalPage,
                }
            };







          
        }


    }
}
